#!/usr/bin/env bash
set -euo pipefail

LIST=${1:-"${0}.vars"}
[ -r "$LIST" ] || { echo "Variable file not found or provided: $LIST" >&2; exit 1; }

while IFS= read -r line || [[ -n $line ]]; do
  line=${line%%#*}
  line="${line#"${line%%[![:space:]]*}"}"
  line="${line%"${line##*[![:space:]]}"}"
  [[ -z $line ]] && continue

  var="$line"

  if [[ ${!var+x} ]]; then
    val="${!var}"
    # escape every baskslash and double
    val=${val//\\/\\\\}
    val=${val//\"/\\\"}
    printf '%s=\"${%s:-%s}\"\n' "$var" "$var" "$val"
  fi
done < "$LIST"
